﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;

namespace Nop.Plugin.Nova.Janrain.Service
{
    public class JanrainEngageService : IJanrainEngageService
    {
        /// <summary>
        /// Get the user profile data from the Engage Service
        /// </summary>
        /// <param name="parameters">String representing token posted from Engage service,apiKey,format,extended</param>
        /// <param name="uri"></param>
        /// <returns></returns>
        public XmlDocument GetJanrainEngageInfo(string parameters, string uri)
        {
            //auth_info
            //parameters = "token=" + Token + "&apiKey=8c04fd573bd8d27d5ec72eda1d04c5f82909c6c6" + "&format=xml&extended=true";
            //uri = "https://rpxnow.com/api/v2/" + "auth_info";


            //contacts
            //parameters = "identifier=" + Identifier + "&apiKey=8c04fd573bd8d27d5ec72eda1d04c5f82909c6c6" + "&format=xml";
            //uri = "https://rpxnow.com/api/v2/" + "get_contacts";


            //make the web request
            WebRequest engageRequest = WebRequest.Create(uri);
            engageRequest.ContentType = "application/x-www-form-urlencoded";
            engageRequest.Method = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(parameters);
            Stream requestStream = null;
            //Post the request to the auth_info REST web service
            try
            {
                engageRequest.ContentLength = bytes.Length;   //Count bytes to send
                requestStream = engageRequest.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);         //Send it
            }
            catch (WebException)
            {
                //Handle WebException error here
                return null;
            }
            finally
            {
                if (requestStream != null)
                {
                    requestStream.Close();
                }
            }
            //Get the response from the auth_info REST web service
            try
            {
                //If there's a web response, then read the stream...otherwise exit the flow
                WebResponse engageResponse = engageRequest.GetResponse();
                if (engageResponse == null) { return null; }
                StreamReader engageStream = new StreamReader(engageResponse.GetResponseStream());
                //Create an XML Document and apply our returned payload to the object
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                doc.LoadXml(engageStream.ReadToEnd().Trim());
                XmlElement documentElement = doc.DocumentElement;
                //Engage error check.  There are 2 possible conditions, either an empty object OR "stat" not equally OK
                if (documentElement == null || !documentElement.GetAttribute("stat").Equals("ok"))
                {
                    // TODO: Handle Unexpected errors
                    // throw new Exception("Unexpected API error");
                }
                return doc;
            }
            catch (WebException)
            {
                //Handle WebException error here
                return null;
            }
        }


    }
}
